package vip.lsjscl.demo.common.controller;

import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import vip.lsjscl.demo.common.manager.ExportTaskManager;
import vip.lsjscl.demo.common.model.ExportProgress;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * 导出控制器 - 简化版
 * 只提供三个接口：
 * 1. SSE接口 - 注册任务并建立SSE连接
 * 2. 处理接口 - 处理数据并生成文件
 * 3. 下载接口 - 下载生成的文件
 *
 * @author zhangxingju
 * @date 2025/03/13
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/api/export")
public class ExportController {

    private final ExportTaskManager taskManager;

    /**
     * 1. SSE接口 - 注册任务并建立SSE连接
     * 创建任务并返回SSE连接，用于实时获取进度
     */
    @GetMapping("/sse")
    public SseEmitter createSseConnection(String taskId) {
        // 创建任务
        taskManager.createTask(taskId);

        // 创建SSE连接
        SseEmitter emitter = taskManager.createSseConnection(taskId);

        // 发送任务ID
        try {
            Map<String, String> data = new HashMap<>();
            data.put("taskId", taskId);
            emitter.send(SseEmitter.event().name("init").data(JSON.toJSONString(data)));
        }
        catch (IOException e) {
            log.error("Failed to send taskId", e);
        }

        return emitter;
    }

    /**
     * 3. 下载接口 - 下载生成的文件
     * 根据任务ID下载生成的文件
     */
    @GetMapping("/download")
    public void downloadFile(String taskId, HttpServletRequest request, HttpServletResponse response) {
        try {
            ExportProgress progress = taskManager.getProgress(taskId);
            if (progress == null || !"COMPLETED".equals(progress.getStatus())) {
                throw new RuntimeException("任务未完成或任务ID不存在");
            }

            String filePath = progress.getFilePath();
            if (filePath == null) {
                throw new RuntimeException("文件路径为空");
            }

            File file = new File(filePath);
            if (!file.exists()) {
                throw new RuntimeException("文件未找到");
            }

            String fileName = file.getName();
            byte[] fileContent = FileUtils.readFileToByteArray(file);

            OutputStream os = response.getOutputStream();
            try {
                if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                    fileName = URLEncoder.encode(fileName, "UTF-8");
                }
                else {
                    fileName = new String(fileName.getBytes(StandardCharsets.UTF_8), "ISO8859-1");
                }
            }
            catch (Exception e) {
                log.error(e.getMessage());
            }
            response.setCharacterEncoding("utf-8");
            //2.设置文件头：最后一个参数是设置下载文件名(假如我们叫a.pdf)
            response.setHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            response.addHeader("Content-Length", String.valueOf(fileContent.length));
            os.write(fileContent);
            os.flush();
            os.close();
        }
        catch (IOException e) {
            log.error("Failed to download file for taskId: {}", taskId, e);
        }
        finally {
            taskManager.deleteTask(taskId);
        }
    }
} 